package accs.model;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;

import accs.model.io.ProxyReader;

public class ExtendedHttpClient extends DefaultHttpClient{
	private static final String DEFAULT_USER_AGENT="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0";
	
	public ExtendedHttpClient(String useragent, String proxyHost, int proxyPort) {
		if(useragent!=null) setUserAgent(useragent);
		if(proxyHost!=null) setProxy(proxyHost, proxyPort);
		
		/*addRequestInterceptor(new HttpRequestInterceptor() {
			public void process(HttpRequest req, HttpContext ctx) throws HttpException, IOException {
				req.setHeader("X-Forwarded-For","127.0.0.1");
				req.setHeader("Via","127.0.0.2");
				req.setHeader("Client-IP","127.0.0.3");
				
//				for(Header h:req.getAllHeaders()) {
//					System.out.println(h.getName()+":"+h.getValue());
//				}
			}
		});*/
	}
	
	public ExtendedHttpClient() {
		this(DEFAULT_USER_AGENT,null,0);
	}
	
	public ExtendedHttpClient(String useragent) {
		this(useragent,null,0);
	}
	
	public ExtendedHttpClient(String proxyHost, int proxyPort) {
		this(DEFAULT_USER_AGENT,proxyHost,proxyPort);
	}
	
	public ExtendedHttpClient(Context ctx) {
		if(ctx!=null) {
			if(ctx.getProxy()!=null) {
				setProxy(ctx.getProxy());
				if(ctx.getProxyAuth()!=null) {
					setProxAuth(ctx.getProxy(),ctx.getProxyAuth());
				}
			}
			if(ctx.getUseragent()!=null) {
				setUserAgent(ctx.getUseragent());
			} else {
				setUserAgent(DEFAULT_USER_AGENT);
			}
		}
	}
	
	private void setProxy(String proxyHost, int proxyPort) {
		getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost,proxyPort));
	}
	
	private void setProxAuth(HttpHost proxy, UsernamePasswordCredentials proxyAuth) {
		getCredentialsProvider().setCredentials(new AuthScope(proxy),proxyAuth);
	}
	
	private void setProxy(HttpHost host) {
		getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
	}
	
	private void setUserAgent(String userAgent) {
		getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
	}
}